//
//  RequestFactory.m
//  Kids
//
//  Created by LiTengFei on 14/11/26.
//  Copyright (c) 2014年 90's Technology Co.Ltd. All rights reserved.
//

#import "RequestFactory.h"
#import "AFNetworking.h"

@interface RequestFactory ()
@property (nonatomic, strong) AFHTTPRequestOperationManager* manager;
@end
@implementation RequestFactory
+ (instancetype)shareFactoryInstace
{
    static RequestFactory* factory;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        factory = [[RequestFactory alloc]init];
        factory.manager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:nil];
        factory.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        factory.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    });
    return factory;
}

+ (void)requestWithRequestData:(RequestData*)data success:(void (^)(AFHTTPRequestOperation*, NSDictionary*))success failure:(void (^)(AFHTTPRequestOperation*, NSError*))failure
{

    [[self shareFactoryInstace] requestWithRequestData:data success:success failure:failure];
}

- (void)requestWithRequestData:(RequestData*)data success:(void (^)(AFHTTPRequestOperation*, NSDictionary*))success failure:(void (^)(AFHTTPRequestOperation*, NSError*))failure
{

    NSString* getURL = [data requestURL];
    
    NSDictionary * params = [data requestParams];
    NSParameterAssert(params);
    NSParameterAssert(getURL);
    

    [self.manager POST:getURL parameters:params success:^(AFHTTPRequestOperation* operation, id responseObject) {
        if([responseObject isKindOfClass:[NSDictionary class]]){
            NSDictionary * dictionary = (NSDictionary *)responseObject;
            success(operation,dictionary);
        }else  if([responseObject isKindOfClass:[NSData class]]){
            NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(operation,dictionary);
        }
    } failure:^(AFHTTPRequestOperation* operation, NSError* error) {
        failure(operation,error);
    }];
}

- (void)requestWithRequestData:(RequestData*)data forResponseData:(ResponseData*)responseData complete:(void (^)(ResponseData*, NSError*))complete
{

    [self requestWithRequestData:data success:^(AFHTTPRequestOperation* operation, NSDictionary* responseObject) {
        
        NSParameterAssert(responseData);
        
        [responseData analyse:responseObject];
        NSLog(@"%@",responseData);
        complete(responseData,nil);

    } failure:^(AFHTTPRequestOperation* operation, NSError* error) {
        
        complete(nil,error);
    }];
}
+ (void)requestWithRequestData:(RequestData*)data forResponseData:(ResponseData*)responseData complete:(void (^)(ResponseData*, NSError*))complete
{
    [[self shareFactoryInstace] requestWithRequestData:data forResponseData:responseData complete:complete];
}

@end
